package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;

@WebServlet("/uploadFileServlet")
@MultipartConfig
public class UploadFileServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {

            //如何设置文件保存位置
            String uploadFilePath=request.getSession().getServletContext().getRealPath("images/");
            File file=new File(uploadFilePath);

            if(!file.exists()){//判断路径是否存在，不存在则创建
                file.mkdirs();//创建目录
            }
            //获取请求中的多个文件
            Collection<Part> parts = request.getParts();
            //循环上传
            for (Part part : parts) {
                String fileName=UUID.randomUUID().toString()+".jpg";
                part.write(uploadFilePath+File.separator+fileName);
            }
            //设置提示信息：
            request.setAttribute("msg","文件上传成功！<br>".concat("文件保存位置：".concat(uploadFilePath)));

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg","文件上传失败！<br> 文件名异常信息："
                    .concat(e.getMessage()));
        }

        request.getRequestDispatcher("upload.jsp").forward(request,response);
    }

}
